/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-01-08 11:05:22
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-04-02 13:59:40
 * @Description: file content
 */

import {
  getCurrentInstance,
  inject,
  reactive,
  ref
} from "@vue/composition-api"

import useCrud from "@/hooks/crud"
import svs_sys_config from "@/service/sys/config"
import objectDeepClone from '@/utils/objectDeepClone'
let root;


export default {
  name: "sys-config",
  setup(props, ctx) {
    return useEnter(props, ctx)
  }
}

/**
 *组合api功能入口。组件中调用。
 *
 * @export
 * @param {*} props_
 * @param {*} ctx_
 * @return {*} 
 */
function useEnter(props_, ctx_) {

  const setups = {
    props: props_,
    ctx: ctx_,
    root: ctx_.root,
    that: getCurrentInstance(),
  }
  root = ctx_.root;
  const msg = inject('globalMessage')

  const options = {
    getConfig(page, condition) {
      return {
        method: "post",
        url: svs_sys_config.api + "/getSearchData",
        data: {
          page: [page.size, page.offset]
        }
      }
    }
  }

  setups.that.$on("get-list", (msg) => {
    console.log(msg);
  })


  let componentRef = ref(null)
  /** dialog打开事件，其中可以拿到form的ref了。 */
  const onDialogOpen = (formRef, dialogState, row) => {
    // console.log(formRef);
    componentRef.value = formRef.getRefs('value')
    if (dialogState === 0) { //判断当前是打开的新增、修改、查看的dialog。
      root.$nextTick(() => {
        componentRef.value.setValue(""); //调用该ref的方法。
      })
    } else if (dialogState === 1) {
      root.$nextTick(() => {
        componentRef.value.setValue(row.value); //调用该ref的方法。
      })
    }
  }


  const cruds = useCrud(options)
  useCrudOption(cruds.option)
  const addSubmit = (data, loading, done) => {
    // console.log(data);
    const sendData = objectDeepClone(data);
    sendData.value = JSON.stringify(JSON.parse(sendData.value))
    svs_sys_config.post(sendData).then(res => {
      // console.log(res);
      if (res.id > 0) {
        msg.saveSuccess();
      }
      loading();
      cruds.refresh();
      root.$store.dispatch('user/getAppConfig');

    })
  }
  const rowEditSubmit = (data, loading, done) => {
    // console.log(data);
    const sendData = objectDeepClone(data);
    sendData.value = JSON.stringify(JSON.parse(sendData.value))
    svs_sys_config.put(data.id, sendData).then(res => {
      // console.log(res);
      if (res.affectedRows > 0) {
        msg.editSuccess();
      }
      loading();
      done();
      cruds.refresh();
      root.$store.dispatch('user/getAppConfig');

    })
  }

  const rowDel = async (scope) => {
    // console.log(scope);
    try {
      await msg.confirm();
      svs_sys_config.delete(scope.row.id).then(res => {
        // console.log(res);
        if (res.affectedRows > 0) {
          msg.deleteSuccess();
          cruds.refresh();
          // 刷新本地配置对象。
          root.$store.dispatch('user/getAppConfig');
        }
      })

    } catch (error) {

    }
  }

  // 初始化时get data
  cruds.refresh();

  // 测试。。拿到数据库系统配置。
  console.log(root.$store.getters.appConfig);

  return {
    ...cruds,
    addSubmit,
    rowEditSubmit,
    rowDel,
    onDialogOpen
  }
}




/**
 *专门处理crud 组件的option配置。
 *
 * @param {*} option
 */
function useCrudOption(option) {
  option.table.column = [{
      label: "名称",
      prop: "name",
      overflow: true,
      form: {
        span: 24,
        componentProps: {
          placeholder: "名称"
        },
        rules: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        }]
      }
    },
    {
      label: "key",
      prop: "key",
      overflow: true,
      form: {
        span: 24,
        componentProps: {
          placeholder: "名称，只能输入英文及下划线_"
        },
        rules: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        }, {
          trigger: 'blur',
          validator(rule, value, callback) {
            const isCorrectFormatUsername = value => /^[a-zA-Z][a-zA-Z0-9_]{0,80}$/g.test(value);
            if (isCorrectFormatUsername(value)) {
              callback();
            } else {
              callback("key必须以字母开头，允许字母、数字、下划线")
            }
          }
        }]
      }
    },
    {
      label: "value",
      prop: "value",
      overflow: true,
      form: {
        index: 0,
        span: 24,
        component: "JsonEditor",
        componentProps: {
          placeholder: "值"
        },
        rules: [{
          required: true,
          message: '请输入',
          trigger: 'blur'
        }, {
          trigger: "blur",
          validator(rule, val, callback) {
            try {
              let a = JSON.parse(val)
              callback()
            } catch (error) {
              callback(new Error("值不符合json格式"))
            }
          }
        }]
      }
    },
    {
      label: "说明",
      prop: "memo",
      overflow: true,
      form: {
        span: 24,
        componentProps: {
          type: "textarea",
          rows: 3,
          placeholder: "备注说明"
        }
      }
    },
  ]

  option.form.labelWidth = "78px";

  /** 搜索查询配置 */
  option.search.items = [{
    label: "查询",
    prop: "search",
    component: "el-input",
    componentProps: {
      placeholder: "请输入内容"
    },
  }]
}
